import { Component, OnInit } from '@angular/core'
import { of, Observable } from 'rxjs'
import { concatMap, map } from 'rxjs/operators'

import { IChannelMap } from '../../components/channels-switcher/channels-switcher.interface'
import { StoreBaseChannelComponent } from './store-base-channel.component'
import { IRouteOfStore } from '@shared/interfaces/store'

@Component({
  selector: 'app-store-edit-channel',
  templateUrl: './store-edit-channel.component.html',
  styles: [],
})
export class StoreEditChannelComponent extends StoreBaseChannelComponent implements OnInit {
  ngOnInit() {
    const routePolicy$ = this.dataService.storeRoute$.value$.pipe(
      concatMap(chan => {
        if (chan.chanCode) {
          return of(chan)
        }

        return this.route.params.pipe(concatMap(params => this.getRoute(params.category, params.id, params.cid)))
      }),
    )

    this.channelsMap$ = routePolicy$.pipe(
      map(route => {
        this.paymentBrand = route.paymentBrand || route.chanCode
        const mp: IChannelMap = {
          [route.chanCode]: route,
        }
        return mp
      }),
    )
  }

  private getRoute(category: string, id: string, cid: string): Observable<IRouteOfStore> {
    if (category === 'qr') {
      return this.storeService.getQRRoute(id, cid)
    } else if (category === 'ec') {
      return this.storeService.getECRoute(id, cid)
    }
    return this.storeService.getCardRoute(id, cid)
  }
}
